<template>
	<!--size抽屉宽度（或高度）  default 378px 和 large 736px -->
	<a-drawer v-model:open="visible" ref="employeeDetailModalRef" class="edit-drawer modal-fixed-bottom"
		root-class-name="root-customer-drawer" width="800px" :closable="false" @close="onClose">
		<div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
		<div class="modal-header">{{ title }}</div>
		<a-form :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol"
			@finish="onSubmit">
			<a-form-item :label="$t('self.businessStation.modal.col3')" name="orgId">
				<a-select v-model:value="formState.orgId" :options="orgOptions"
					:fieldNames="{label: 'orgName',value: 'id'}" :placeholder="$t('self.pleaseChoose')"
					@change="getTariffPolicy" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.tips1')" name="stationName">
				<a-input allow-clear v-model:value="formState.stationName" placeholder="" />
			</a-form-item>
			<!--      省市区暂时屏蔽-->
			<!--      <a-form-item :label="$t('self.businessStation.modal.col4')" name="stationArea">-->
			<!--        <choose-area-for-local v-model:value="areaArr" placeholder="" @change="handleChangeArea"></choose-area-for-local>-->
			<!--      </a-form-item>-->
			<a-form-item :label="$t('self.businessStation.modal.col4')" name="stationArea">
				<a-input allow-clear v-model:value="formState.stationArea" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.modal.col5')" name="stationAreaDetail">
				<a-input allow-clear v-model:value="formState.stationAreaDetail" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.tips3')" name="longitude">
				<a-input allow-clear v-model:value="formState.longitude" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.tips4')" name="latitude">
				<a-input allow-clear v-model:value="formState.latitude" placeholder="" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.modal.col6')" name="tariffPolicy">
				<a-select v-model:value="formState.tariffPolicy" :options="tariffPolicyOptions"
					:fieldNames="{label: 'policyName',value: 'id'}" :placeholder="$t('self.pleaseChoose')" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.modal.col7')" name="mobile">
				<a-input allow-clear v-model:value="formState.mobile" placeholder="" />
			</a-form-item>

			<a-form-item :label="$t('self.businessStation.modal.col8')" name="operatingStatus">
				<a-select v-model:value="formState.operatingStatus" :options="[
            { label: $t('self.businessStation.statusType.tips1'), value: 0 },
            { label: $t('self.businessStation.statusType.tips2'), value: 1 },
            { label: $t('self.businessStation.statusType.tips3'), value: 2 },
        ]" />
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.modal.col13')" name="characteristic">
				<a-select mode="multiple" v-model:value="formState.characteristic" :options="cdqjkOptions"
					:fieldNames="{label: 'label',value: 'key'}" :placeholder="$t('self.pleaseChoose')" />
			</a-form-item>

			<!-- 			<a-form-item :label="$t('self.businessStation.modal.col14')" name="supportingFacilities">
				<a-select v-model:value="formState.supportingFacilities" :options="[
			        { label: $t('self.businessStation.supportingFacilitiesType.tips1'), value: 0 },
			        { label: $t('self.businessStation.supportingFacilitiesType.tips2'), value: 1 },
			    ]">
					<template #option="{ label }">
						{{ label }}
					</template>
				</a-select>
			</a-form-item> -->
			<a-form-item :label="$t('self.businessStation.modal.col8')" name="supportingFacilities">
				<a-select mode="multiple" v-model:value="formState.supportingFacilities"
					:options="supportingFacilitiesOptions" />
			</a-form-item>

			<!--充电接口-->
			<a-form-item :label="$t('self.businessCharging.tips16')" name="chargeInterface">
				<a-select mode="multiple" v-model:value="formState.chargeInterface" :options="cdqjkOptions1"
					:fieldNames="{label: 'label',value: 'key'}" :placeholder="$t('self.pleaseChoose')" />
			</a-form-item>
			
			<div class="base-flex  base-align-items-left base-justify-content-left">
			
				<div v-for="pics in allAdv">
					<div
						style="border: 1px solid #ccc;width: 60px;text-align: center;padding-top: 5px;margin-left: 10px;">
						<p style="margin-bottom: 0px;" v-if="pics.indexOf('.jpg')!=-1||pics.indexOf('.png')!=-1">
							<img :src="pics" style="width: 50px;height: 50px;margin-bottom: 0px;"></img>
						</p>
						<p style="margin-bottom: 0px;" v-else>
							<img src="@/assets/mp4.png" style="width: 50px;height: 50px;margin-bottom: 0px;"></img>
						</p>
						<p style="color: red;margin-bottom: 0px;cursor: pointer;margin-bottom: 0px;">
							<img @click="deletePileAdv(pics)" :lang="pics" src="@/assets/delete.png"
								style="width: 15px;height: 15px;margin-bottom: 0px;"></img>
						</p>
					</div>
				</div>
			
			</div>
<!-- 			<a-form-item :label="$t('self.businessStation.modal.col9')" name="">
				<a-upload 
				v-model:file-list="uploadParams.pic1" 
				name="avatar" list-type="picture-card"
					class="uploader-wrapper1" 
					:show-upload-list="true" 
					:headers="uploadParams.header"
					:action="uploadParams.url"
					:data="uploadParams.data"
					:on-success="handleSuccess"
					@change="handleUploadChange">
					<div class="base-flex base-columns base-align-items-center base-justify-content-center">
						<plus-outlined class="base-f20 gui-color-grey2" />
						<div class="ant-upload-text gui-color-grey base-mt10">Upload</div>
					</div>
				</a-upload>
				<div class="gui-color-grey2">{{ $t('self.operators.tips38') }}：375px *
					500px，1M{{ $t('self.businessStation.modal.col11') }}</div>
			</a-form-item>
			<a-form-item :label="$t('self.businessStation.modal.col10')" name="">
				<a-upload v-model:file-list="uploadParams.pic2" name="avatar"
					list-type="picture-card"
					class="uploader-wrapper1"
					:show-upload-list="true"
					:action="uploadParams.url"
					@change="handleUploadChange"
					>
					<div class="base-flex base-columns base-align-items-center base-justify-content-center">
						<plus-outlined class="base-f20 gui-color-grey2" />
						<div class="ant-upload-text gui-color-grey base-mt10">Upload</div>
					</div>
				</a-upload>
				<div class="gui-color-grey2">{{ $t('self.businessStation.modal.col12') }}1M</div>
			</a-form-item> -->

			<div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
				<a-button type="primary" html-type="submit">{{ $t('self.submitButton') }}</a-button>
				<a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
			</div>

		</a-form>

	</a-drawer>
</template>

<script setup>
	import {
		computed,
		getCurrentInstance,
		onMounted,
		ref
	} from 'vue'
	import {
		message
	} from 'ant-design-vue'
	import chooseAreaForLocal from '@/components/choose/choose-area-for-local.vue'
	const {
		proxy
	} = getCurrentInstance()
	const $TOOL = proxy.$TOOL
	const $API = proxy.$API
	const $T = proxy.$t
	const emit = defineEmits(['close', 'ok'])
	const allAdv = ref([])
	const visible = ref(false)
	// 模式，add新增，show查看，edit编辑
	const mode = ref('add')
	const labelCol = {
		style: {
			width: '230px',
		},
	};
	const wrapperCol = {
		span: 16,
	};
	const title = ref('')
	const formState = ref({
		id: '',
		orgId: null,
		stationName: '',
		stationProvince: '',
		stationCity: '',
		stationArea: '',
		stationAreaDetail: '',
		longitude: '',
		latitude: '',
		tariffPolicy: null,
		mobile: '',
		operatingStatus: 0, // 0：待开通、1：维护中、2：运营中
		chargeInterface: [],
		characteristic: [],
		supportingFacilities: 0,
	})
	const areaArr = ref([]) // 省市区的集合
	const orgOptions = ref([])
	const tariffPolicyOptions = ref([]) // 资费的下拉列表
	const uploadParams = ref({
		url: '',
		header: {

		},
		pic1: [], // 场站图片，多张
		pic2: [], // 广告图，多张
	})
	const cdqjkOptions = ref([{
			label: 'Rest room',
			key: 'Rest room'
		},
		{
			label: 'Parking facility',
			key: 'Parking facility'
		},
		{
			label: 'Power backup',
			key: 'Power backup'
		}
	])
	const supportingFacilitiesMap = {
		'E-MOTOS': 0,
		'E-CARS': 1,
	};

	const supportingFacilitiesOptions = [{
			label: 'E-MOTOS',
			value: 'E-MOTOS'
		},
		{
			label: 'E-CARS',
			value: 'E-CARS'
		},
	];
	// 充电接口的下拉列表
	const cdqjkOptions1 = ref([{
			label: 'Type 2',
			key: 'Type 2'
		},
		{
			label: 'SAE J1772',
			key: 'SAE J1772'
		},
		{
			label: 'CHAdeMO',
			key: 'CHAdeMO'
		},
		{
			label: 'GB/T',
			key: 'GB/T'
		},
		{
			label: 'Tesla',
			key: 'Tesla'
		}
	])
	const formRules = ref({
		orgId: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessStation.modal.col3'),
			trigger: 'change'
		}],
		stationName: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.tips1'),
			trigger: 'change'
		}],
		stationArea: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.modal.col4'),
			trigger: 'change'
		}],
		stationAreaDetail: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.modal.col5'),
			trigger: 'change'
		}],
		longitude: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.tips3'),
			trigger: 'change'
		}],
		latitude: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.tips4'),
			trigger: 'change'
		}],
		tariffPolicy: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.modal.col6'),
			trigger: 'change'
		}],
		mobile: [{
			required: true,
			message: $T('self.pleaseInput') + $T('self.businessStation.modal.col7'),
			trigger: 'change'
		}],
		operatingStatus: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.modal.col8'),
			trigger: 'change'
		}],
		supportingFacilities: [{
			required: true,
			message: $T('self.pleaseChoose') + $T('self.businessCharging.modal.col14'),
			trigger: 'change'
		}],
	})

	onMounted(async () => {
		orgOptions.value = await proxy.getOrgSelectList(true)
	})

	const getTariffPolicy = async () => {
		tariffPolicyOptions.value = await proxy.getTariffPolicySelectListByOrg(formState.value.orgId)
	}

	const handleUploadChange = (info) => {
		if (info.file.status !== 'uploading') {
			console.log(info.file, info.fileList);
		}
		if (info.file.status === 'done') {
			// message.success(`${info.file.name} file uploaded successfully`);
		} else if (info.file.status === 'error') {
			// message.error(`${info.file.name} file upload failed.`);
		}
	}

	const handleChangeArea = (area) => {
		formState.value.stationProvince = area[0]
		formState.value.stationCity = area[1]
		formState.value.stationArea = area[2]
	}

	const onSubmit = (values) => {
		const params = {
			...formState.value
		}

		// 将 characteristic 数组转换为逗号分隔的字符串，并过滤掉空字符串
		if (Array.isArray(params.characteristic)) {
			params.characteristic = params.characteristic.filter(item => item).join(',');
		}

		if (Array.isArray(params.chargeInterface)) {
			params.chargeInterface = params.chargeInterface.filter(item => item).join(',');
		}
		params.supportingFacilities = supportingFacilitiesMap[params.supportingFacilities];

		console.log("params.supportingFacilities==", params.supportingFacilities)

		if (mode.value === 'add') {
			// 添加
			$API.backend.businessStation.add.post(params).then(res => {
				message.success($T('self.message.success'))
				onReset()
				visible.value = false
				emit('ok')
			}).catch(err => {
				message.error(err.msg);
			})
		} else {
			// 修改
			$API.backend.businessStation.edit.post(params).then(res => {
				message.success($T('self.message.success'))
				onReset()
				visible.value = false
				emit('ok')
			}).catch(err => {
				message.error(err.msg);
			})
		}
	}
	const handleSuccess = (response, file, fileList)=> {
		console.log('服务器返回:', response);
		if(response.code==200){

		}
	}
	const deletePileAdv = (data) => {
		// data=data.replace(`${ config.static_URL }`,"");
		data = data.substring(data.lastIndexOf('/') + 1, data.length);
		var params = {
			"id": formState.value.id,
			'adv': data
		}
		console.log(params);
		$API.backend.businessCharging.deletePileAdv.post(params).then(res => {
			const {
				objData,
				code
			} = res
			console.log(objData, code);
			if (code == 200) {
				getPileAdv('');
			} else {
				message.error(err.msg);
			}
		}).catch(err => {
			message.error(err.msg);
		})
	}
	const getPileAdv = (data) => {
		//data=data.replace(`${ config.static_URL }`,"");
		var params = {
			"id": formState.value.id
		}
		console.log(params);
		$API.backend.businessCharging.getPileAdv.post(params).then(res => {
			const {
				objData,
				code
			} = res
			console.log(objData, code);
			if (code == 200) {
				var files = objData;
				allAdv.value = [];
				if (files != "" && files != null) {
					var fs = files.split(',');
					for (let i = 0; i < fs.length; i++) {
						var t = `${ config.static_URL }/uploadFile/adv/` + fs[i];
						allAdv.value[i] = t;
					}
				}
				console.log(allAdv);
			} else {
				message.error($T('self.message.error'))
			}
		}).catch(err => {
			message.error($T('self.message.error'))
		})
	}
	const onReset = () => {
		// 清空内容
		areaArr.value = []
		allAdv.value = []
		tariffPolicyOptions.value = []
		formState.value = {
			id: '',
			orgId: null,
			stationName: '',
			stationProvince: '',
			stationCity: '',
			stationArea: '',
			stationAreaDetail: '',
			longitude: '',
			latitude: '',
			tariffPolicy: '',
			mobile: '',
			operatingStatus: 0,
			chargeInterface: [],
			characteristic: [], //提供的服务
			supportingFacilities: 0,
		}
	}

	const onClose = () => {
		onReset()
		visible.value = false
		emit('close')
	}

	const add = () => {
		mode.value = 'add'
		title.value = $T('self.businessStation.modal.col1')
		visible.value = true
	}

	const edit = (record) => {
		mode.value = 'edit'
		// 克隆存在的键
		$TOOL.array.cloneExistKey(formState.value, record)

		// 解析 characteristic 字段
		if (record.characteristic) {
			formState.value.characteristic = record.characteristic.split(',').map(item => item.trim());
		} else {
			formState.value.characteristic = [];
		}

		if (record.chargeInterface) {
			formState.value.chargeInterface = record.chargeInterface.split(',').map(item => item.trim());
		} else {
			formState.value.chargeInterface = [];
		}
		switch (record.supportingFacilities) {
			case 0:
				formState.value.supportingFacilities = 'E-MOTOS';
				break;
			case 1:
				formState.value.supportingFacilities = 'E-CARS';
				break;
			default:
				formState.value.supportingFacilities = '';
				break;
		}
		//   if (record.supportingFacilities) {
		// 	formState.value.supportingFacilities = record.supportingFacilities.split(',').map(item => item.trim());
		// } else {
		// 	formState.value.supportingFacilities = [];
		// }
		// 直接赋值 supportingFacilities 的文字值
		// formState.value.supportingFacilities = record.supportingFacilities;

		// 将 operatingStatus 从字符串转换为数字
		formState.value.operatingStatus = parseInt(record.operatingStatus, 10);

		title.value = $T('self.businessStation.modal.col2') + '：' + formState.value.stationName
		visible.value = true

		if (formState.value.orgId) {
			getTariffPolicy()
		}
	}

	// 子组件中要通过defineExpose将方法暴露给父组件
	defineExpose({
		add,
		edit
	})
</script>

<style lang="scss" scoped>
	.edit-drawer {
		position: relative;

		.closeable {
			@include closeable;
		}
	}
</style>